import React, { Component } from 'react'
import {connect} from 'react-redux'
import {CProduct} from '../../../types/product'
import CarItem from '../../../component/car-item/car-item'
import request from '../../../util/request'
interface IProps{
    carList:CProduct[],
    initCarList: (list:CProduct[]) =>void,
    history:any
}

class Car extends Component<IProps>{
    render() {
        let carList = this.props.carList;
        return (
            <div>
                {carList.length && carList.map((item:CProduct) => <CarItem key={item.id} item={item}></CarItem>)}
                <div>
                    {/* 全选 */}
                    {/* <input type="checkbox"/> */}
                    {/* 下单 */}
                    <button onClick={this.subOrder}>提交订单</button>
                </div>
            </div>
        )
    }

    //提交订单
    subOrder = () => {
        //选中的提交，没有选中不提交
        let products = this.props.carList.filter((item:CProduct) => item.checked); //[{},[]]
        

        //对象字符串  JSON.stringify
        request.post('/api/addOrder',{products:JSON.stringify(products)}).then(res => {
            
            if(res.data.code === 1){
                console.log("订单提交成功");
                //1.已购买的商品需要删除 carList
                let notProducts  = this.props.carList.filter((item:CProduct) => !item.checked);
                this.props.initCarList(notProducts);
                //2.跳到订单列表界面
                this.props.history.push('/order')
            }
        })
    }
}

let stateMapToProps = (state:any) => {return {
    carList:state.car.carList
}}

let dispatchMapToProps = (dispacth:any) => {
    return {
        initCarList(list:CProduct[]){
            dispacth({type:'INIT_LIST',list})
        }
    }
}

export default connect(stateMapToProps,dispatchMapToProps)(Car)